package com.ffapp.f9164.td.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.BasisFragment;
import com.ffapp.f9164.td.basis.Constants;
import com.ffapp.f9164.td.bean.ParamListData;
import com.ffapp.f9164.td.util.CountDown;
import com.ffapp.f9164.td.util.EditTextUtil;
import com.ffapp.f9164.td.util.SoftKeyBoardListener;
import com.ffapp.f9164.td.util.SubstringUtil;
import com.ffapp.f9164.td.view.PopHandle;
import com.suke.widget.SwitchButton;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.LogUtil;

public class StorageFragment extends BasisFragment {

    static StorageFragment fragment;

    public static StorageFragment newInstance() {
        if (fragment == null) {
            fragment = new StorageFragment();
        }
        return fragment;
    }

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> centerList;
    ArrayList<ParamListData> originalList;
    public static int SUBMIT = 75;

    private boolean isFinish = false;
    private int showLineNum;  //要显示的数量

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();
    private String atShowString;

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < centerList.size()) {
                        initSettingSaveThred(subPosition);
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        originalList.clear();
                        originalList.addAll(centerList);
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            PopHandle popHandle = new PopHandle(getActivity(), "tips_fail", "错误信息", saveResult.toString());
                            popHandle.show();
                        } else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    if (!isFinish) {
                        showToast("设置失败，请重试");
                        dismissProgress();
                        BleUtils.stopNotify();
                    }
                    break;
            }

        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
            openNotify();
        } else {
            LogUtil.d("终端fragment隐藏");
            BleUtils.stopNotify();
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_center);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
//                submitHandler.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
//                          submitHandler.postDelayed(Constants.SUBMIT,20000);   //20秒后执行
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        centerList = new ArrayList<>();
        originalList = new ArrayList<>();
    }

    private void openNotify() {
        BleUtils.notify(new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {

            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                String sMes = HexUtil.bytesToAscii(data);
//                showToast(sMes);
//                showToast(terminalData.getName() + "保存成功");
                if (sMes.contains("OK")) {
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }
            }

            @Override
            public void onError() {
                saveResult.append(centerList.get(subPosition - 1).getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }
        });
    }

    private void setAction(){
//        BleUtils.write(toSet, new BleWriteCallback() {
//            @Override
//            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
//                if (current == total) {
//                    mCountDownTimer.start();
//                }
//            }
//
//            @Override
//            public void onWriteFailure(final BleException exception) {
//                saveResult.append(centerList.get(position).getName() + "下发失败" + "\r\n");
//            }
//        });
    }

    public void setList(String sMsgObjString, int type) {
        centerList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {
            atShowString = sMsgObjString;
            List<String> connectTypeList = Arrays.asList(getResources().getStringArray(R.array.aisle));
            //占位
            centerList.add(new ParamListData("备选服务器", 86, "aaaa", ""));

            //备选主服务器
            String bkSvr = SubstringUtil.subString(sMsgObjString, "BK Svr's 1");
            String bkSvrString = SubstringUtil.getStringBeforeKey(bkSvr, ",");
            centerList.add(new ParamListData("备选信道连接方式", 1, "" + bkSvrString, connectTypeList, "AT+BKSVRTYP"));
            String bkAddress = SubstringUtil.getStringAfterKey(bkSvr, ",");
            centerList.add(new ParamListData("备选中心地址", 2, "" + bkAddress, "AT+IPSEC", ""));

            //占位
            centerList.add(new ParamListData("主服务器", 86, "aaaa", ""));
            //服务器数量
            String totalServersValue = SubstringUtil.subString(sMsgObjString, "Total Servers:");
            if (TextUtils.isEmpty(totalServersValue)) {
                totalServersValue = "1";
                showLineNum = 1;
            } else {
                showLineNum = Integer.valueOf(totalServersValue);
            }
            ArrayList<String> serviceNumList = new ArrayList<>();
            serviceNumList.add("1");
            serviceNumList.add("2");
            serviceNumList.add("3");
            serviceNumList.add("4");
            centerList.add(new ParamListData("服务器数量", 1, "" + totalServersValue, serviceNumList, "AT+SVRCNT"));

            String[] mainSvr = {"Main Svr's 1:", "Main Svr's 2:", "Main Svr's 3:", "Main Svr's 4:"};
            String[] svrType = {"AT+SVRTYP", "AT+SVRTYP1", "AT+SVRTYP2", "AT+SVRTYP3"};
            String[] svrParam = {"AT+IPAD", "AT+IPAD1", "AT+IPAD2", "AT+IPAD3"};

            for (int i = 0; i < showLineNum; i++) {
                //例子sMsgObjString =  Main Svr's 1:TCP,120.42.46.98:5003
                //中心地址
                String dataString = SubstringUtil.subString(sMsgObjString, "" + mainSvr[i]);    //dataString = TCP,120.42.46.98:5003
                String key = SubstringUtil.getStringBeforeKey(dataString, ",");
                centerList.add(new ParamListData("信道连接方式", 1, "" + key, connectTypeList, "" + svrType[i]));
                String value = SubstringUtil.getStringAfterKey(dataString, ",");
                centerList.add(new ParamListData("中心" + (i + 1) + "地址", 2, "" + value, "" + svrParam[i]));
            }
            if (type == Constants.AT_FROM_DEVICE) {
                originalList.addAll(centerList);
            }
        }
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_terminal_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return centerList == null ? 0 : centerList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                if (position < showLineNum * 2 + 5) {
                    list_item.setVisibility(View.VISIBLE);
                    ParamListData centerListData = centerList.get(position);
                    tvName.setText(centerListData.getName());
                    switch (centerListData.getType()) {
                        case 1: //spinner
                            editText.setText("" + (TextUtils.isEmpty(centerListData.getValue()) ? centerListData.getKey() : centerListData.getValue()));
                            editText.setHint("请选择" + centerListData.getName());
                            imgSpanner.setVisibility(View.VISIBLE);
                            tvUnit.setVisibility(View.GONE);
                            switchBtn.setVisibility(View.GONE);
                            editText.setEnabled(false);//不可编辑
                            list_item.setBackgroundResource(R.color.white);
                            break;
                        case 2:  // edit
                            editText.setText("" + centerListData.getValue());
                            editText.setHint("请输入" + centerListData.getName());
                            tvUnit.setVisibility(View.GONE);
                            imgSpanner.setVisibility(View.GONE);
                            switchBtn.setVisibility(View.GONE);
                            editText.setEnabled(true);//可编辑
                            editText.setVisibility(View.VISIBLE);
                            list_item.setBackgroundResource(R.color.white);
                            break;
                        case 86:   //分隔作用
                            imgSpanner.setVisibility(View.GONE);
                            tvUnit.setVisibility(View.GONE);
                            switchBtn.setVisibility(View.GONE);
                            editText.setVisibility(View.GONE);
                            list_item.setBackgroundResource(R.color.base_bg_white);
                            break;
                    }
                    editText.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            int curPosition = getAdapterPosition();
                            ParamListData data = centerList.get(curPosition);
                            centerList.set(curPosition, new ParamListData(data.getName(), data.getType(), s.toString(), data.getValues(), data.getAction(), data.getKey(), data.getIsOpen(), data.getUnit()));
                        }
                    });
                    imgSpanner.setTag(position);
                } else {
                    list_item.setVisibility(View.GONE);
                }
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final int position = (int) v.getTag();
                final ParamListData centerData = centerList.get(position);
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String optionValue = centerData.getValues().get(options1);
                        editText.setText(optionValue);
                        if (centerData.getName().equals("服务器数量")) {
                            centerList.get(position).setKey(optionValue);
                            showLineNum = Integer.valueOf(optionValue);
                        }
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(centerData.getValues());
                pickerView.show();

            }
        }
    }


    @OnClick(R.id.btn_save)
    public void save() {
        showLoading();
        saveResult.setLength(0);
        subPosition = 0;
        submitHandler.sendEmptyMessage(Constants.SUBMIT);
    }

    public void initSettingSaveThred(final int position) {
        String url = getBlueToothUrl(centerList.get(position));

        String originalurl = getBlueToothUrl(originalList.get(position));
        if (TextUtils.isEmpty(originalurl)) {
            originalurl = "";
        }
        if (originalurl.equals(url)) {
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }

        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {
                    mCountDownTimer.start();
                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                saveResult.append(centerList.get(position).getName() + "下发失败" + "\r\n");
            }
        });


    }


    private String getBlueToothUrl(ParamListData data) {
        String url;
        String name = data.getName();
        String at = data.getAction();
        String value = (data.getValue() == null) ? data.getKey() : data.getValue();
        if (TextUtils.isEmpty(value)) {
            value = "";
        }

        String a = null;
        try {
            a = HexUtil.chineseWordToGbk((at + "=" + value + "\r\n"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url = a;
    }

}
